﻿Imports System.Math
Public Class grupbox1
    Public empresas As Integer
    Public bodegas As Integer
    Public costo As Integer = 0
    Public matriz(10, 10) As PanelClasss
    Private numeroAleatorio As Integer
    Private sumaBodega As Integer
    Private sumaEmpresa As Integer
    Private contador As Integer
    Private metodosParaPanel As New PanelClasss
    Private nivelJuego As Integer = 0
    Private juegoCargado As Boolean = False
    Private contadorClick As Integer = 0
    Private esRandom As Boolean = False
    Private verificar As New verificacion
    Private contadorDeJugadas As Integer = 0
    Dim costoInicial As Integer = 0
    Dim CostoFinal As Integer = 0
    Dim metodo As Integer 'para identificar cual metodo se utilizo



    Public Sub btnGenerar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerar.Click
        btnRandom.Enabled = True
        btnGenerar.Enabled = False
        Timer1.Start()
        grupbox1_Load(Nothing, Nothing)
        costo = 0

        empresas = Integer.Parse(NumEmpresas.Text)
        bodegas = Integer.Parse(NumBodegas.Text)

        For i As Integer = 1 To empresas
            For j As Integer = 1 To bodegas
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is Panel Then
                        i = i.ToString
                        j = j.ToString
                        If elemento.Name = "Panel" & i & j Then
                            ''hacemos solamente visible los paneles que se deben mostrar
                            elemento.Visible = True
                            'inicializar panel'
                            If juegoCargado = False Then
                                inicializarPanel(elemento)
                            End If
                            ''instanciamso la clase panel
                            Dim panelFantasma As New PanelClasss
                            'del elemento grafico obtenemos el costo en este caso el 2 es textbox 1 es el label de asignación 0 es el label de verificacion
                            panelFantasma.costo = Integer.Parse(elemento.Controls.Item(2).Text)
                            'guardamos el objeto en la matriz con los valores si tenemos los datos en la matriz la hacemos toda'
                            panelFantasma.fila = i
                            panelFantasma.columna = j
                            matriz(i, j) = panelFantasma
                        End If
                    End If
                    If TypeOf elemento Is NumericUpDown Then
                        If elemento.Name = "NumericUpDown" & i & j Or elemento.Name = "NumericUpDow" & i & j Then
                            elemento.Visible = True
                        End If
                    End If
                Next
            Next
        Next

    End Sub


    Private Sub grupbox1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ocultarPaneles(splitContainer1.Panel1)
        sumaBodega = 0
        sumaEmpresa = 0
        contador = 0
        inicializarMatriz()
    End Sub
    Public Sub inicializarMatriz()
        'inicializamos una matriz con el tamaño de la empresa y  la bodega, ver si se debe asignar cuando
        ' se agregue la otra columna para balancear
        For i As Integer = 1 To empresas
            For j As Integer = 1 To bodegas
                Dim objetoVacio As New PanelClasss
                objetoVacio.asignacion = 0
                objetoVacio.costo = 0
                objetoVacio.espacioBodega = 0
                objetoVacio.produccionEmpresa = 0
                objetoVacio.verificacion = 0
                matriz(i, j) = objetoVacio
            Next
        Next
    End Sub
    Private Sub btnIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIniciar.Click
        optimizar.Enabled = False
        'primero verificar balanceo'
        'al momento de verifica'
        contadorClick += 1

        nivelJuego += 1
        Timer1.Start()
        btnRandom.Enabled = False
        Dim diferencia As Integer = verificarBalanceo()
        If sumaBodega < sumaEmpresa Then
            If NumBodegas.Value < 5 Then
                NumBodegas.Value = NumBodegas.Value + 1
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is NumericUpDown Then
                        If elemento.Name = "NumericUpDow1" & NumBodegas.Value Then
                            Dim espacioBodega As NumericUpDown
                            espacioBodega = elemento
                            espacioBodega.Value = diferencia
                            elemento.Text = diferencia
                            For Each label As Control In splitContainer1.Panel1.Controls
                                If TypeOf label Is Label Then
                                    If label.Name = "UpDow1" & NumBodegas.Value Then
                                        Dim nuevo As Label
                                        nuevo = label
                                        nuevo.Text = diferencia
                                    End If
                                End If
                            Next
                        End If
                    End If
                Next
            Else
                MessageBox.Show("Se ha sobrepasado el tamaño de la matriz al intentar equilibrar el problema ")
            End If
            Call btnGenerar_Click(Nothing, Nothing)
            btnRandom.Enabled = False
        ElseIf sumaBodega > sumaEmpresa Then

            If NumEmpresas.Value < 5 Then
                NumEmpresas.Value = NumEmpresas.Value + 1
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is NumericUpDown Then
                        If elemento.Name = "NumericUpDown" & NumEmpresas.Value & "1" Then
                            Dim espacioEmpresa As NumericUpDown
                            espacioEmpresa = elemento
                            espacioEmpresa.Value = diferencia
                            elemento.Text = diferencia
                            For Each label As Control In splitContainer1.Panel1.Controls
                                If TypeOf label Is Label Then
                                    If label.Name = "UpDown" & NumEmpresas.Value & "1" Then
                                        Dim nuevo As Label
                                        nuevo = label
                                        nuevo.Text = diferencia
                                    End If
                                End If
                            Next
                        End If
                    End If
                Next
                Call btnGenerar_Click(Nothing, Nothing)
                btnRandom.Enabled = False
            Else
                MessageBox.Show("Se ha sobrepasado el tamaño de la matriz al intentar equilibrar el problema ")
            End If
        Else

            'tomar los costos de los paneles y almacenarlos en la matriz'
            For i As Integer = 1 To empresas
                For j As Integer = 1 To bodegas
                    For Each elemento As Control In splitContainer1.Panel1.Controls
                        If TypeOf elemento Is Panel Then
                            If elemento.Name = "Panel" & i & j Then
                                elemento.Controls.Item(1).Text = ""
                                elemento.Controls.Item(0).Text = ""
                                elemento.Controls.Item(0).Enabled = False
                                matriz(i, j).costo = elemento.Controls.Item(2).Text
                                matriz(i, j).asignacion = 0
                                matriz(i, j).verificacion = 0
                                matriz(i, j).fila = 0
                                matriz(i, j).columna = 0
                                matriz(i, j).espacioBodega = 0
                                matriz(i, j).produccionEmpresa = 0
                            End If
                        End If
                    Next
                Next
            Next

            'tomar las capacidades de produccion y almacenaje y guardarlas en label ocultos'
            For i As Integer = 1 To empresas
                For j As Integer = 1 To bodegas
                    For Each elemento As Control In splitContainer1.Panel1.Controls
                        If TypeOf elemento Is NumericUpDown Then
                            If elemento.Name = "NumericUpDown" & i & 1 Then
                                For Each label As Control In splitContainer1.Panel1.Controls
                                    If TypeOf label Is Label Then
                                        If label.Name = "UpDown" & i & 1 Then
                                            label.Text = elemento.Text
                                        End If
                                    End If
                                Next
                            End If
                            If elemento.Name = "NumericUpDow" & 1 & j Then
                                For Each label As Control In splitContainer1.Panel1.Controls
                                    If TypeOf label Is Label Then
                                        If label.Name = "UpDow" & 1 & j Then
                                            label.Text = elemento.Text
                                        End If
                                    End If
                                Next
                            End If
                        End If
                    Next
                Next
            Next
            'debemos sentenciar que tipo de juego se llevará cabo

            'If cwn.checked = True Then
            If rdCWM.Checked = True Then
                metodo = 1
                Dim metodosCWM As New CWM
                metodosCWM.juguemosCWM()
            ElseIf rdMMC.Checked = True Then
                metodo = 2
                Dim metodosMMC As New MMC
                metodosMMC.juguemosMMC()
            ElseIf rdVogel.Checked = True Then
                metodo = 3
                Dim metodosVogel As New Vogel
                metodosVogel.jueguemosVogel()
            ElseIf rdRussel.Checked = True Then
                metodo = 4
                Dim metodosRussell As New Russell
                metodosRussell.juguemosRussell()
            End If
            Btnverif.Enabled = True
            'tomar los valores de la matriz y mostrarlos en los paneles'
            For i As Integer = 1 To empresas
                For j As Integer = 1 To bodegas
                    For Each elemento As Control In splitContainer1.Panel1.Controls
                        If elemento.Name = "Panel" & i & j Then
                            If matriz(i, j).asignacion > 0 Then
                                elemento.Controls.Item(1).Text = matriz(i, j).asignacion
                                elemento.Controls.Item(1).Visible = True
                                ' elemento.Controls.Item(0).Text = matriz(i, j).verificacion
                                'elemento.Controls.Item(0).Visible = True
                            End If
                        End If
                    Next
                Next
            Next
            calcular_costo()
            btnIniciar.Enabled = False
        End If

        btnIniciar.Text = "Jugar"


    End Sub
    Private Sub inicializarPanel(ByVal panel As Panel)
        'así tambien cambiaremos los datos graficamente'
        panel.Controls.Item(1).Text = ""
        panel.Controls.Item(0).Visible = False
    End Sub

    Private Sub btnRandom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRandom.Click
        Dim random As New Random(DateTime.Now.Millisecond)
        esRandom = True
        For i As Integer = 1 To empresas
            For j As Integer = 1 To bodegas
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is Panel Then
                        i = i.ToString
                        j = j.ToString
                        If elemento.Name = "Panel" & i & j Then
                            Dim numeroAleatorio As Integer = random.Next(1, 100)
                            elemento.Controls.Item(2).Text = numeroAleatorio
                        End If
                    End If
                    If TypeOf elemento Is NumericUpDown Then
                        If elemento.Name = "NumericUpDown" & i & 1 Or elemento.Name = "NumericUpDow" & 1 & j Then
                            Dim numeroAleatorio As Integer = random.Next(1, 100)
                            elemento.Controls.Item(1).Text = numeroAleatorio

                        End If
                    End If
                Next
            Next
        Next


    End Sub

    Public Function verificarBalanceo()


        For i As Integer = 1 To empresas
            For Each elemento As Control In splitContainer1.Panel1.Controls
                If TypeOf elemento Is NumericUpDown Then
                    If elemento.Name = "NumericUpDown" & i & 1 Then
                        sumaEmpresa = sumaEmpresa + Integer.Parse(elemento.Controls.Item(1).Text)
                    End If
                End If
            Next
        Next
        For i As Integer = 1 To bodegas
            For Each elemento As Control In splitContainer1.Panel1.Controls
                If TypeOf elemento Is NumericUpDown Then
                    If elemento.Name = "NumericUpDow" & 1 & i Then
                        sumaBodega = sumaBodega + Integer.Parse(elemento.Controls.Item(1).Text)
                    End If
                End If
            Next
        Next

        Return Abs(sumaBodega - sumaEmpresa)

    End Function
    Private Sub guardarJuego(ByVal estado As Integer, ByVal metodo As Integer)
        'MsgBox(costoInicial & " " & CostoFinal)
        metodosParaPanel.guardarJuego(empresas, bodegas, statusHora.Text, estado, costoInicial, CostoFinal, metodo, contadorDeJugadas)
        metodosParaPanel.almacenarPaneles()
        Timer1.Stop()
    End Sub
    Public Sub BtnReiniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnReiniciar.Click
        Label52.Text = ""
        Label54.Text = ""
        Label53.Text = ""
        btnIniciar.Text = "Balancear"
        optimizar.Enabled = False
        contadorDeJugadas = 0
        nivelJuego = 0
        btnIniciar.Enabled = True
        btnGenerar.Enabled = True
        btnRandom.Enabled = True
        grupbox1_Load(Nothing, Nothing)
        NumBodegas.Value = 2
        NumEmpresas.Value = 2
        For i As Integer = 1 To 5
            For j As Integer = 1 To 5
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If elemento.Name = "Panel" & i & j Then
                        elemento.Controls.Item(1).Text = ""
                        elemento.Controls.Item(0).Text = ""
                        elemento.Controls.Item(0).Visible = False
                        elemento.Controls.Item(2).Text = 0
                        elemento.Enabled = True
                    ElseIf elemento.Name = "NumericUpDown" & i & 1 Then
                        elemento.Text = 1
                    ElseIf elemento.Name = "NumericUpDow" & 1 & j Then
                        elemento.Text = 1
                    ElseIf elemento.Name = "UpDown" & i & 1 Then
                        elemento.Text = ""
                    ElseIf elemento.Name = "UpDow" & 1 & j Then
                        elemento.Text = ""
                    ElseIf elemento.Name = "u" & i Then
                        elemento.Text = ""
                    ElseIf elemento.Name = "v" & i Then
                        elemento.Text = ""
                    End If
                Next
            Next
        Next

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        statusHora.Text = DateTime.Now
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        FrmEleccionJuego.ShowDialog()
    End Sub
    Public Sub ingresarPanelesMatriz()
        For i As Integer = 1 To empresas
            For j As Integer = 1 To bodegas
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is Panel Then
                        i = i.ToString
                        j = j.ToString
                        If elemento.Name = "Panel" & i & j Then
                            ''hacemos solamente visible los paneles que se deben mostrar

                            ''instanciamso la clase panel
                            Dim panelFantasma As New PanelClasss
                            'del elemento grafico obtenemos el costo en este caso el 2 es textbox 1 es el label de asignación 0 es el label de verificacion

                            panelFantasma.costo = Integer.Parse(elemento.Controls.Item(2).Text)
                            If elemento.Controls.Item(0).Text <> "" Then
                                panelFantasma.verificacion = Integer.Parse(elemento.Controls.Item(0).Text)
                            End If
                            'guardamos el objeto en la matriz con los valores si tenemos los datos en la matriz la hacemos toda'
                            If elemento.Controls.Item(1).Text = "-" Or elemento.Controls.Item(1).Text = "" Then
                                panelFantasma.asignacion = 0
                            ElseIf elemento.Controls.Item(1).Text = 0 Then
                                panelFantasma.asignacion = -1
                            Else
                                panelFantasma.asignacion = Integer.Parse(elemento.Controls.Item(1).Text)
                            End If
                            panelFantasma.fila = i
                            panelFantasma.columna = j
                            matriz(i, j) = panelFantasma
                        End If
                    End If

                Next
            Next
        Next
    End Sub
    Private Sub btnGuardarJuego_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuardarJuego.Click
        'si el boton random no se apretó y y está balanceada nivel de juego es 2
        If esRandom = False Then
            ingresarPanelesMatriz()
        End If
        If verificarBalanceo() = 0 Then
            guardarJuego(nivelJuego, metodo)
            metodosParaPanel.almacenarCapacidades()
            MsgBox("Juego Almacenado Correctamente")
        Else
            MsgBox("Matriz no balanceada")
        End If

    End Sub
    Public Sub cargarPanelesEnJuego()
        empresas = Integer.Parse(NumEmpresas.Text)
        bodegas = Integer.Parse(NumBodegas.Text)
        juegoCargado = True
        For i As Integer = 1 To empresas
            For j As Integer = 1 To bodegas
                For Each elemento As Control In splitContainer1.Panel1.Controls
                    If TypeOf elemento Is Panel Then
                        i = i.ToString
                        j = j.ToString
                        If elemento.Name = "Panel" & i & j Then
                            inicializarPanel(elemento)
                            elemento.Controls.Item(2).Text = matriz(i, j).costo
                            elemento.Controls.Item(0).Text = matriz(i, j).verificacion
                            elemento.Controls.Item(0).Visible = True
                            If matriz(i, j).asignacion > 0 Then
                                elemento.Controls.Item(1).Text = matriz(i, j).asignacion
                            ElseIf matriz(i, j).asignacion = 0 Then
                                elemento.Controls.Item(1).Text = ""
                            Else
                                elemento.Controls.Item(1).Text = 0
                            End If
                        End If
                    End If
                    If TypeOf elemento Is NumericUpDown Then
                        If elemento.Name = "NumericUpDown" & i & j Or elemento.Name = "NumericUpDow" & i & j Then
                            elemento.Visible = True
                        End If
                    End If
                Next
            Next
        Next
        btnGenerar_Click(Nothing, Nothing)
    End Sub

    Private Sub Btnverif_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btnverif.Click
        Btnverif.Enabled = False
        verificar.limpiar()
        verificar.verificar()
        verificar.revisar()
        If verificar.neg Then
            optimizar.Enabled = True
        End If
    End Sub

    Private Sub rdCWM_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdCWM.CheckedChanged
        btnIniciar.Enabled = True
    End Sub

    Private Sub rdMMC_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdMMC.CheckedChanged
        btnIniciar.Enabled = True
    End Sub

    Private Sub rdVogel_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdVogel.CheckedChanged
        btnIniciar.Enabled = True
    End Sub

    Private Sub rdRussel_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdRussel.CheckedChanged
        btnIniciar.Enabled = True
    End Sub


    Private Sub txtCosto1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCosto1.Click
        txtCosto1.Text = ""
    End Sub

    Private Sub TextBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Click
        TextBox2.Text = ""
    End Sub

    Private Sub TextBox3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.Click
        TextBox3.Text = ""
    End Sub

    Private Sub optimizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optimizar.Click
        calcular_costo()
        costoInicial = Label52.Text.Substring(7)
        While verificar.neg
            Dim metodosSimplex As New Simplex
            Dim arreglo(2) As Integer
            Dim contadorRuta As Integer = 1
            arreglo = metodosSimplex.obtenerMovimientoInicial()
            If arreglo(0) <> 0 Then
                metodosSimplex.jugarSimplex(arreglo(0), arreglo(1), contadorRuta)
            End If
            contadorDeJugadas += 1
            'MsgBox(contadorDeJugadas)
            PanelAMatriz()
            verificar.limpiar()
            verificar.verificar()
            verificar.revisar()
        End While
        Label53.Text = "Iteraciones: " & contadorDeJugadas
        Label53.Visible = True
        calcular_costo()
        CostoFinal = Label52.Text.Substring(7)
        Label52.Text = "Costo Inicial: " & FormatNumber(costoInicial, 0)
        Label54.Text = "Costo Final  : " & FormatNumber(CostoFinal, 0)
        'MsgBox(costoInicial & " " & CostoFinal)
    End Sub
End Class
